import Taro from "@tarojs/taro";
import { Middleware, registerMiddleware, Router } from "tarojs-router-next";

export const AuthCheck: Middleware<{ mustLogin: boolean }> = async (
  ctx,
  next,
) => {
  if (ctx.route.ext?.mustLogin) {
    const token = Taro.getStorageSync("token");
    if (!token) {
      const { confirm } = await Taro.showModal({
        title: "提示",
        content: "请先登录",
      });

      if (confirm) Router.toLogin();

      // 直接返回，不执行 next 即可打断中间件向下执行
      return;
    }
  }

  await next();
};

registerMiddleware(AuthCheck);
